package com.example.tofcamera;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Environment;
import android.util.Log;
import android.view.Surface;

import com.vm.lib.NativeWarpper;


/**
 * Created by jhanbin on 16/1/2018.
 */

public class DisplayFrameThread extends Thread {

    public static int[] vertex = null;

    public static void DisplayBitmap(Surface surface, Bitmap bmp)
    {
        if(surface!=null && surface.isValid())
        {
            Canvas c = surface.lockCanvas(null);
            if (c != null) {
                c.drawBitmap(bmp, 0, 0, null);
            }
            surface.unlockCanvasAndPost(c);
        }
    }

    public static void DisplayMemoryToSurface(Surface surface, FrameQueue frameQueue)
    {
        int i=0;
        byte []data= new byte[0];

        try {
            data = frameQueue.take().getData();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        int []dataRGBA=new int[frameQueue.getFrameWidth()*frameQueue.getFrameHeight()];
        Bitmap bmp=Bitmap.createBitmap(frameQueue.getFrameWidth(), frameQueue.getFrameHeight(), Bitmap.Config.ARGB_8888);

        while(data!=null)
        {
//            Log.d("DisplayMemoryToSurface", "post "+(i++));

            NativeWarpper.DrawRoiRGBA(frameQueue.getFrameWidth(), frameQueue.getFrameHeight(),data,dataRGBA,vertex);

//            try {
//                new Frame(data).SaveRaw(Environment.getExternalStorageDirectory().getAbsolutePath()+"/uv.bin");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }

//            dataRGBA=Frame.ToInt(data);

            bmp.setPixels(dataRGBA, 0, frameQueue.getFrameWidth(), 0, 0, frameQueue.getFrameWidth(), frameQueue.getFrameHeight());


            DisplayBitmap(surface,            Bitmap.createScaledBitmap(bmp, 1200, 900, false)            );

            try {
                data=frameQueue.take().getData();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    protected Surface surface;
    protected FrameQueue frameQueue;



    public DisplayFrameThread(Surface surface, FrameQueue frameQueue) {
        this.surface=surface;
        this.frameQueue=frameQueue;
    }

    @Override
    public void run() {
            DisplayMemoryToSurface(surface, frameQueue);
    }

}
